<?php
/**
 * Created by PhpStorm.
 * User: zxqc2018
 * Date: 2018/12/24
 * Time: 17:46
 */

namespace App\Model;

use Illuminate\Database\Eloquent\Model;

/**
 * model基类
 * Class BaseModel
 * @package App\Model
 * @author zxqc2018
 */
class BaseModel extends Model
{
    public $timestamps = false;

    /**
     * 数据插入
     * @param array|Model $data 数据
     * @return null
     * @author zxqc2018
     */
    public function simpleCreate($data)
    {
        $model = null;

        if (is_array($data)) {
            //假定有设置白名单  或者 黑名单
            if (!empty($this->fillable) && empty(array_diff(array_keys($data), $this->fillable)) ||
                empty($this->fillable) && !empty($this->guarded) && current($this->guarded) != '*' && empty(array_intersect($this->guarded, array_keys($data)))) {
                $model = static::create($data);
                return $model;
            } else {
                $model = new static();
                foreach ($data as $d_key => $d_val) {
                    $model->{$d_key} = $d_val;
                }
            }
        }

        if ($data instanceof Model) {
            $model = $data;
        }

        if (!is_null($model)) {

            $model->save();
        }

        return $model;
    }

    /**
     * 数据更新
     * @param array $where 条件数组
     * @param array $data 更新数据
     * @return mixed
     * @author zxqc2018
     */
    public function simpleUpdate($where, $data)
    {
        $res =  $this->where($where)->update($data);
        return $res;
    }

    /**
     * 查询单条数据
     * @param string|array $key
     * @param mixed $value 值
     * @param string $field 查询字段
     * @return array
     * @author zxqc2018
     */
    public function findOne($key, $value = null, $field = '*')
    {
        $res = [];

        //条件的纠正判断
        if(!is_array($key) && is_null($value)){
            return $res;
        }

        if (is_array($key)) {
            $where = $key;
            //纠正['id', 1] 为 [['id', 1]] 这样的条件可以写成 ['id' => 1]
            if (isset($where[0]) && !is_array($where[0])) {
                $where = [$key];
            }
        } else {
            $where = [$key => $value];
        }

        $rowData = static::where($where)->selectRaw($field)->first();

        if (!is_null($rowData)) {
            $res = $rowData->toArray();
        }
        return $res;
    }
}
